package me.pcqpcq.android.aclean;

import java.io.File;

import me.pcqpcq.android.Constant;
import me.pcqpcq.android.mgr.ActivityMgr;
import me.pcqpcq.android.msg.MessageCentre;
import me.pcqpcq.android.util.FileInfoUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class CleanApkActivity extends Activity {

	private String apkDirsStr = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityMgr.setCurActivity(CleanApkActivity.this);
		setContentView(R.layout.act_clean_apk);
	}

	/**
	 * APK清理的点击事件
	 * @param v
	 */
	public void onCleanApkTap(View v) {
		switch (v.getId()) {

		case R.id.btn_start:
			// 检查是否已设置清理目录
			if (isSetCleanList()) {
				String[] apkDirs = apkDirsStr.split(",");
				new CleanApkTask().execute(apkDirs);
			}
			break;

		case R.id.btn_refresh:
			break;

		case R.id.btn_back:
			onBackPressed();
			break;

		default:
			break;
		}
	}

	class CleanApkTask extends AsyncTask<String[], Void, Object> {

		@Override
		protected Object doInBackground(String[]... params) {
			startCleanApk(params[0]);
			return null;
		}

		@Override
		protected void onPreExecute() {
			// 显示进度框
			MessageCentre.showProgressDlg(getString(R.string.pd_cleanning_apk_dirs), "");
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Object result) {
			// 修改视图
			Button startBtn = (Button) findViewById(R.id.btn_start);
			startBtn.setVisibility(View.GONE);
			TextView cleanFinish = (TextView) findViewById(R.id.label_apk_dirs_finish);
			cleanFinish.setVisibility(View.VISIBLE);
			// 关闭进度框
			MessageCentre.closeProgressDlg();
			super.onPostExecute(result);
		}

	}

	/**
	 * 检查是否已设置清理目录
	 */
	private boolean isSetCleanList() {
		boolean isCheck = false;
		SharedPreferences sharedPreferences = getSharedPreferences(Constant.PREFERENCE_CLEAN_LIST, MODE_PRIVATE);
		apkDirsStr = sharedPreferences.getString("apk_dirs", "");
		if (apkDirsStr.equals("")) {
			Builder noApkDirsDlg = new AlertDialog.Builder(CleanApkActivity.this);
			noApkDirsDlg.setTitle(getString(R.string.dlg_title_hint));
			noApkDirsDlg.setMessage(getString(R.string.dlg_msg_no_apk_dirs));
			noApkDirsDlg.setPositiveButton(getString(R.string.btn_ok), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent();
					intent.setClass(CleanApkActivity.this, SettingCleanActivity.class);
					startActivity(intent);
				}
			});
			noApkDirsDlg.setNegativeButton(getString(R.string.btn_cancle), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			noApkDirsDlg.show();
		} else
			isCheck = true;
		return isCheck;
	}

	/**
	 * 执行清理操作
	 */
	private void startCleanApk(String[] apkDirs) {
		// 循环所有指定的目录
		for (String apkDir : apkDirs) {
			if (!"".equals(apkDir)) {
				File apkDirFile = new File(apkDir);
				// 获取一个目录下所有的文件
				File[] apkFiles = apkDirFile.listFiles();
				// 循环此目录下的所有文件
				for (File apkFile : apkFiles) {
					// 如果文件是APK安装包
					if (apkFile.getName().endsWith(".apk")) {
						// 解析APK的安装名
						String apkPath = apkFile.getAbsolutePath();
						String apkInstalledNamePrefix = FileInfoUtil.getApkInstalledName(apkPath);
						String apkInstalledName = apkInstalledNamePrefix.concat(".apk");
						if (!"".equals(apkInstalledName)) {
							String apkInstalledPath = apkFile.getParent().concat("/").concat(apkInstalledName);
							// 实际操作文件！
							// 如果已存在相同文件
							File apkInstalledFile = new File(apkInstalledPath);
							if (apkInstalledFile.exists()) {
								// 对比版本号以及包名，删除旧版本
								String apkInstalledVersion = FileInfoUtil.getApkInfo(apkInstalledPath, FileInfoUtil.INFO_TYPE_VERSION);
								String apkInstalledPkg = FileInfoUtil.getApkInfo(apkInstalledPath, FileInfoUtil.INFO_TYPE_PACKAGE);
								String apkVersion = FileInfoUtil.getApkInfo(apkPath, FileInfoUtil.INFO_TYPE_VERSION);
								String apkPkg = FileInfoUtil.getApkInfo(apkPath, FileInfoUtil.INFO_TYPE_PACKAGE);
								if (apkInstalledPkg != null && apkPkg != null) {
									// 如果包名一致
									if (apkInstalledPkg.equals(apkPkg)) {
										if (apkInstalledVersion != null && apkVersion != null) {
											// 如果apkInstalledVersion < apkVersion
											// 则删除apkInstalledVersion
											if (apkInstalledVersion.compareToIgnoreCase(apkVersion) < 0) {
												apkInstalledFile.delete();
											} else if (apkInstalledVersion.compareToIgnoreCase(apkVersion) > 0) {
												apkFile.delete();
											}
										}
									}
								}
							} else {
								String fileNameForCheck = apkInstalledFile.getName();
								String fileNameChecked = checkFileName(fileNameForCheck);
								if (!fileNameForCheck.equals(fileNameChecked)) {
									String filePathChecked = apkInstalledFile.getParent().concat("/").concat(fileNameChecked);
									apkInstalledFile = new File(filePathChecked);
								}
								apkFile.renameTo(apkInstalledFile);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * <p> 检查文件名
	 * <p> 检查文件名是否包含特殊字符
	 * <p> 特殊字符包括：\/:*?"<>|
	 * @param fileNameForCheck 文件名
	 */
	private String checkFileName(String fileNameForCheck) {
		String REPLACEMENT = "";
		String newName = fileNameForCheck;
		newName = fileNameForCheck.replaceAll("\\\\|/|:|\\*|\\?|\\\"|<|>|\\|", REPLACEMENT);
		return newName;
	}

}